﻿using System;
using System.Collections.Generic;
using System.Data;
//using System.Data.SqlClient;
using System.Data.SQLite;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace SuperSqlOperation.Sqlite
{
    /// <summary>
    /// 创建表
    /// </summary>
    static class CreateSqlExecute
    {
        public static async Task<int> CreateExecute<T>(this IDbConnection conn )
        {
            Type t = typeof(T);
            PropertyInfo[] propertyInfo = t.GetProperties();
            string tableName = t.GetDataTableNameByAttr(); //获得特性定义的表名称 
            StringBuilder cloumnStr = new StringBuilder(); 
           
            foreach (PropertyInfo property in propertyInfo)
            {
                if (property.GetDataIgnoreByAttr()) continue;  //过滤掉特性定义的需要忽略的属性
                if (!property.GetDataWriteByAttr()) continue;  //过滤掉特性定义的是否可写的属性 定义为false则忽略 
                if (!property.PropertyType.IsValueType && !property.PropertyType.Equals(typeof(string))) continue;  //过滤掉泛型以及非基础类型的数据类型

                string colConfig = string.Empty;
                if (property.GetDataKeyByAttr()) colConfig = " PRIMARY KEY AUTOINCREMENT NOT NULL "; // 主键自增1 且非空

                string columnName = property.GetDataColumnByAttr();
                // var columnValue = property.GetValue(model) == null ? DBNull.Value : property.GetValue(model);
                string dataType = property.GetSqlType();
                cloumnStr.Append(columnName + " " + dataType + " " + colConfig + ","); 
            }

            string sqlCommandText = string.Format("CREATE TABLE {0} ( {1} )", tableName, cloumnStr.ToString().TrimEnd(','));
            //-----------------
            int insertId = 0;
            using (conn)
            {
                try
                {  
                    SQLiteCommand comm = conn.CreateCommand() as SQLiteCommand;
                    comm.CommandText = sqlCommandText;
                    // comm.Parameters.AddRange(par.ToArray()); 
                    conn.Open();
                    //insertId = await Task.Run(() => comm.ExecuteNonQuery());
                    insertId = await comm.ExecuteNonQueryAsync();
                    conn.Close(); 
                }
                catch (Exception)
                {
                    conn.Close();
                }
            }
            return 0;

        }
    }

}
